package com.yoshino.leetcode.interview150.Kadane;

class Solution {
    public int maxSubArray(int[] nums) {
        int res = nums[0], temp = res;
        for (int i = 1; i < nums.length; i++) {
            temp = temp > 0 ? temp + nums[i] : nums[i];
            if (res < temp) {
                res = temp;
            }
        }
        return res;
    }

    public int maxSubarraySumCircular(int[] A) {
//        最大子数组 不成环 --- 53题 也就是maxSum为答案
//        最大子数组 成环 ，那么最小子数组就不会成环 --- (total - minSum) 则为答案
        int sum = 0, lineMax = A[0], curMax = 0, lineMin = A[0], curMin = 0;
        for (int i : A) {
            curMax = Math.max(curMax + i, i);
            curMin = Math.min(curMin + i, i);
            lineMax = Math.max(lineMax, curMax);
            lineMin = Math.min(lineMin, curMin);
            sum += i;
        }
        // 全为负数的时候，第一个值为 0，错误
        return lineMax > 0 ? Math.max(lineMax, sum - lineMin) : lineMax;
    }
}